{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 9.20 \u5229\u7528\u51fd\u6570\u6ce8\u89e3\u5b9e\u73b0\u65b9\u6cd5\u91cd\u8f7d\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u95ee\u9898\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f60\u5df2\u7ecf\u5b66\u8fc7\u600e\u6837\u4f7f\u7528\u51fd\u6570\u53c2\u6570\u6ce8\u89e3\uff0c\u90a3\u4e48\u4f60\u53ef\u80fd\u4f1a\u60f3\u5229\u7528\u5b83\u6765\u5b9e\u73b0\u57fa\u4e8e\u7c7b\u578b\u7684\u65b9\u6cd5\u91cd\u8f7d\u3002\n\u4f46\u662f\u4f60\u4e0d\u786e\u5b9a\u5e94\u8be5\u600e\u6837\u53bb\u5b9e\u73b0\uff08\u6216\u8005\u5230\u5e95\u884c\u5f97\u901a\u4e0d\uff09\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u89e3\u51b3\u65b9\u6848\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u672c\u5c0f\u8282\u7684\u6280\u672f\u662f\u57fa\u4e8e\u4e00\u4e2a\u7b80\u5355\u7684\u6280\u672f\uff0c\u90a3\u5c31\u662fPython\u5141\u8bb8\u53c2\u6570\u6ce8\u89e3\uff0c\u4ee3\u7801\u53ef\u4ee5\u50cf\u4e0b\u9762\u8fd9\u6837\u5199\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "class Spam:\n    def bar(self, x:int, y:int):\n        print('Bar 1:', x, y)\n\n    def bar(self, s:str, n:int = 0):\n        print('Bar 2:', s, n)\n\ns = Spam()\ns.bar(2, 3) # Prints Bar 1: 2 3\ns.bar('hello') # Prints Bar 2: hello 0"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e0b\u9762\u662f\u6211\u4eec\u7b2c\u4e00\u6b65\u7684\u5c1d\u8bd5\uff0c\u4f7f\u7528\u5230\u4e86\u4e00\u4e2a\u5143\u7c7b\u548c\u63cf\u8ff0\u5668\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# multiple.py\nimport inspect\nimport types\n\nclass MultiMethod:\n    '''\n    Represents a single multimethod.\n    '''\n    def __init__(self, name):\n        self._methods = {}\n        self.__name__ = name\n\n    def register(self, meth):\n        '''\n        Register a new method as a multimethod\n        '''\n        sig = inspect.signature(meth)\n\n        # Build a type signature from the method's annotations\n        types = []\n        for name, parm in sig.parameters.items():\n            if name == 'self':\n                continue\n            if parm.annotation is inspect.Parameter.empty:\n                raise TypeError(\n                    'Argument {} must be annotated with a type'.format(name)\n                )\n            if not isinstance(parm.annotation, type):\n                raise TypeError(\n                    'Argument {} annotation must be a type'.format(name)\n                )\n            if parm.default is not inspect.Parameter.empty:\n                self._methods[tuple(types)] = meth\n            types.append(parm.annotation)\n\n        self._methods[tuple(types)] = meth\n\n    def __call__(self, *args):\n        '''\n        Call a method based on type signature of the arguments\n        '''\n        types = tuple(type(arg) for arg in args[1:])\n        meth = self._methods.get(types, None)\n        if meth:\n            return meth(*args)\n        else:\n            raise TypeError('No matching method for types {}'.format(types))\n\n    def __get__(self, instance, cls):\n        '''\n        Descriptor method needed to make calls work in a class\n        '''\n        if instance is not None:\n            return types.MethodType(self, instance)\n        else:\n            return self\n\nclass MultiDict(dict):\n    '''\n    Special dictionary to build multimethods in a metaclass\n    '''\n    def __setitem__(self, key, value):\n        if key in self:\n            # If key already exists, it must be a multimethod or callable\n            current_value = self[key]\n            if isinstance(current_value, MultiMethod):\n                current_value.register(value)\n            else:\n                mvalue = MultiMethod(key)\n                mvalue.register(current_value)\n                mvalue.register(value)\n                super().__setitem__(key, mvalue)\n        else:\n            super().__setitem__(key, value)\n\nclass MultipleMeta(type):\n    '''\n    Metaclass that allows multiple dispatch of methods\n    '''\n    def __new__(cls, clsname, bases, clsdict):\n        return type.__new__(cls, clsname, bases, dict(clsdict))\n\n    @classmethod\n    def __prepare__(cls, clsname, bases):\n        return MultiDict()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e3a\u4e86\u4f7f\u7528\u8fd9\u4e2a\u7c7b\uff0c\u4f60\u53ef\u4ee5\u50cf\u4e0b\u9762\u8fd9\u6837\u5199\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "class Spam(metaclass=MultipleMeta):\n    def bar(self, x:int, y:int):\n        print('Bar 1:', x, y)\n\n    def bar(self, s:str, n:int = 0):\n        print('Bar 2:', s, n)\n\n# Example: overloaded __init__\nimport time\n\nclass Date(metaclass=MultipleMeta):\n    def __init__(self, year: int, month:int, day:int):\n        self.year = year\n        self.month = month\n        self.day = day\n\n    def __init__(self):\n        t = time.localtime()\n        self.__init__(t.tm_year, t.tm_mon, t.tm_mday)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e0b\u9762\u662f\u4e00\u4e2a\u4ea4\u4e92\u793a\u4f8b\u6765\u9a8c\u8bc1\u5b83\u80fd\u6b63\u786e\u7684\u5de5\u4f5c\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s = Spam()\ns.bar(2, 3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s.bar('hello')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s.bar('hello', 5)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s.bar(2, 'hello')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Overloaded __init__\nd = Date(2012, 12, 21)\n# Get today's date\ne = Date()\ne.year"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "e.month"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "e.day"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u8ba8\u8bba\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5766\u767d\u6765\u8bb2\uff0c\u76f8\u5bf9\u4e8e\u901a\u5e38\u7684\u4ee3\u7801\u800c\u5df2\u672c\u8282\u4f7f\u7528\u5230\u4e86\u5f88\u591a\u7684\u9b54\u6cd5\u4ee3\u7801\u3002\n\u4f46\u662f\uff0c\u5b83\u5374\u80fd\u8ba9\u6211\u4eec\u6df1\u5165\u7406\u89e3\u5143\u7c7b\u548c\u63cf\u8ff0\u5668\u7684\u5e95\u5c42\u5de5\u4f5c\u539f\u7406\uff0c\n\u5e76\u80fd\u52a0\u6df1\u5bf9\u8fd9\u4e9b\u6982\u5ff5\u7684\u5370\u8c61\u3002\u56e0\u6b64\uff0c\u5c31\u7b97\u4f60\u5e76\u4e0d\u4f1a\u7acb\u5373\u53bb\u5e94\u7528\u672c\u8282\u7684\u6280\u672f\uff0c\n\u5b83\u7684\u4e00\u4e9b\u5e95\u5c42\u601d\u60f3\u5374\u4f1a\u5f71\u54cd\u5230\u5176\u5b83\u6d89\u53ca\u5230\u5143\u7c7b\u3001\u63cf\u8ff0\u5668\u548c\u51fd\u6570\u6ce8\u89e3\u7684\u7f16\u7a0b\u6280\u672f\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u672c\u8282\u7684\u5b9e\u73b0\u4e2d\u7684\u4e3b\u8981\u601d\u8def\u5176\u5b9e\u662f\u5f88\u7b80\u5355\u7684\u3002MutipleMeta \u5143\u7c7b\u4f7f\u7528\u5b83\u7684 __prepare__() \u65b9\u6cd5\n\u6765\u63d0\u4f9b\u4e00\u4e2a\u4f5c\u4e3a MultiDict \u5b9e\u4f8b\u7684\u81ea\u5b9a\u4e49\u5b57\u5178\u3002\u8fd9\u4e2a\u8ddf\u666e\u901a\u5b57\u5178\u4e0d\u4e00\u6837\u7684\u662f\uff0c\nMultiDict \u4f1a\u5728\u5143\u7d20\u88ab\u8bbe\u7f6e\u7684\u65f6\u5019\u68c0\u67e5\u662f\u5426\u5df2\u7ecf\u5b58\u5728\uff0c\u5982\u679c\u5b58\u5728\u7684\u8bdd\uff0c\u91cd\u590d\u7684\u5143\u7d20\u4f1a\u5728 MultiMethod\n\u5b9e\u4f8b\u4e2d\u5408\u5e76\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "MultiMethod \u5b9e\u4f8b\u901a\u8fc7\u6784\u5efa\u4ece\u7c7b\u578b\u7b7e\u540d\u5230\u51fd\u6570\u7684\u6620\u5c04\u6765\u6536\u96c6\u65b9\u6cd5\u3002\n\u5728\u8fd9\u4e2a\u6784\u5efa\u8fc7\u7a0b\u4e2d\uff0c\u51fd\u6570\u6ce8\u89e3\u88ab\u7528\u6765\u6536\u96c6\u8fd9\u4e9b\u7b7e\u540d\u7136\u540e\u6784\u5efa\u8fd9\u4e2a\u6620\u5c04\u3002\n\u8fd9\u4e2a\u8fc7\u7a0b\u5728 MultiMethod.register() \u65b9\u6cd5\u4e2d\u5b9e\u73b0\u3002\n\u8fd9\u79cd\u6620\u5c04\u7684\u4e00\u4e2a\u5173\u952e\u7279\u70b9\u662f\u5bf9\u4e8e\u591a\u4e2a\u65b9\u6cd5\uff0c\u6240\u6709\u53c2\u6570\u7c7b\u578b\u90fd\u5fc5\u987b\u8981\u6307\u5b9a\uff0c\u5426\u5219\u5c31\u4f1a\u62a5\u9519\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e3a\u4e86\u8ba9 MultiMethod \u5b9e\u4f8b\u6a21\u62df\u4e00\u4e2a\u8c03\u7528\uff0c\u5b83\u7684 __call__() \u65b9\u6cd5\u88ab\u5b9e\u73b0\u4e86\u3002\n\u8fd9\u4e2a\u65b9\u6cd5\u4ece\u6240\u6709\u6392\u9664 slef \u7684\u53c2\u6570\u4e2d\u6784\u5efa\u4e00\u4e2a\u7c7b\u578b\u5143\u7ec4\uff0c\u5728\u5185\u90e8map\u4e2d\u67e5\u627e\u8fd9\u4e2a\u65b9\u6cd5\uff0c\n\u7136\u540e\u8c03\u7528\u76f8\u5e94\u7684\u65b9\u6cd5\u3002\u4e3a\u4e86\u80fd\u8ba9 MultiMethod \u5b9e\u4f8b\u5728\u7c7b\u5b9a\u4e49\u65f6\u6b63\u786e\u64cd\u4f5c\uff0c__get__() \u662f\u5fc5\u987b\u5f97\u5b9e\u73b0\u7684\u3002\n\u5b83\u88ab\u7528\u6765\u6784\u5efa\u6b63\u786e\u7684\u7ed1\u5b9a\u65b9\u6cd5\u3002\u6bd4\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "b = s.bar\nb"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "b.__self__"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "b.__func__"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "b(2, 3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "b('hello')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e0d\u8fc7\u672c\u8282\u7684\u5b9e\u73b0\u8fd8\u6709\u4e00\u4e9b\u9650\u5236\uff0c\u5176\u4e2d\u4e00\u4e2a\u662f\u5b83\u4e0d\u80fd\u4f7f\u7528\u5173\u952e\u5b57\u53c2\u6570\u3002\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s.bar(x=2, y=3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s.bar(s='hello')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e5f\u8bb8\u6709\u5176\u4ed6\u7684\u65b9\u6cd5\u80fd\u6dfb\u52a0\u8fd9\u79cd\u652f\u6301\uff0c\u4f46\u662f\u5b83\u9700\u8981\u4e00\u4e2a\u5b8c\u5168\u4e0d\u540c\u7684\u65b9\u6cd5\u6620\u5c04\u65b9\u5f0f\u3002\n\u95ee\u9898\u5728\u4e8e\u5173\u952e\u5b57\u53c2\u6570\u7684\u51fa\u73b0\u662f\u6ca1\u6709\u987a\u5e8f\u7684\u3002\u5f53\u5b83\u8ddf\u4f4d\u7f6e\u53c2\u6570\u6df7\u5408\u4f7f\u7528\u65f6\uff0c\n\u90a3\u4f60\u7684\u53c2\u6570\u5c31\u4f1a\u53d8\u5f97\u6bd4\u8f83\u6df7\u4e71\u4e86\uff0c\u8fd9\u65f6\u5019\u4f60\u4e0d\u5f97\u4e0d\u5728 __call__() \u65b9\u6cd5\u4e2d\u5148\u53bb\u505a\u4e2a\u6392\u5e8f\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u540c\u6837\u5bf9\u4e8e\u7ee7\u627f\u4e5f\u662f\u6709\u9650\u5236\u7684\uff0c\u4f8b\u5982\uff0c\u7c7b\u4f3c\u4e0b\u9762\u8fd9\u79cd\u4ee3\u7801\u5c31\u4e0d\u80fd\u6b63\u5e38\u5de5\u4f5c\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "class A:\n    pass\n\nclass B(A):\n    pass\n\nclass C:\n    pass\n\nclass Spam(metaclass=MultipleMeta):\n    def foo(self, x:A):\n        print('Foo 1:', x)\n\n    def foo(self, x:C):\n        print('Foo 2:', x)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u539f\u56e0\u662f\u56e0\u4e3a x:A \u6ce8\u89e3\u4e0d\u80fd\u6210\u529f\u5339\u914d\u5b50\u7c7b\u5b9e\u4f8b\uff08\u6bd4\u5982B\u7684\u5b9e\u4f8b\uff09\uff0c\u5982\u4e0b\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "s = Spam()\na = A()\ns.foo(a)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "c = C()\ns.foo(c)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "b = B()\ns.foo(b)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f5c\u4e3a\u4f7f\u7528\u5143\u7c7b\u548c\u6ce8\u89e3\u7684\u4e00\u79cd\u66ff\u4ee3\u65b9\u6848\uff0c\u53ef\u4ee5\u901a\u8fc7\u63cf\u8ff0\u5668\u6765\u5b9e\u73b0\u7c7b\u4f3c\u7684\u6548\u679c\u3002\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import types\n\nclass multimethod:\n    def __init__(self, func):\n        self._methods = {}\n        self.__name__ = func.__name__\n        self._default = func\n\n    def match(self, *types):\n        def register(func):\n            ndefaults = len(func.__defaults__) if func.__defaults__ else 0\n            for n in range(ndefaults+1):\n                self._methods[types[:len(types) - n]] = func\n            return self\n        return register\n\n    def __call__(self, *args):\n        types = tuple(type(arg) for arg in args[1:])\n        meth = self._methods.get(types, None)\n        if meth:\n            return meth(*args)\n        else:\n            return self._default(*args)\n\n    def __get__(self, instance, cls):\n        if instance is not None:\n            return types.MethodType(self, instance)\n        else:\n            return self"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e3a\u4e86\u4f7f\u7528\u63cf\u8ff0\u5668\u7248\u672c\uff0c\u4f60\u9700\u8981\u50cf\u4e0b\u9762\u8fd9\u6837\u5199\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "class Spam:\n    @multimethod\n    def bar(self, *args):\n        # Default method called if no match\n        raise TypeError('No matching method for bar')\n\n    @bar.match(int, int)\n    def bar(self, x, y):\n        print('Bar 1:', x, y)\n\n    @bar.match(str, int)\n    def bar(self, s, n = 0):\n        print('Bar 2:', s, n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u63cf\u8ff0\u5668\u65b9\u6848\u540c\u6837\u4e5f\u6709\u524d\u9762\u63d0\u5230\u7684\u9650\u5236\uff08\u4e0d\u652f\u6301\u5173\u952e\u5b57\u53c2\u6570\u548c\u7ee7\u627f\uff09\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u6240\u6709\u4e8b\u7269\u90fd\u662f\u5e73\u7b49\u7684\uff0c\u6709\u597d\u6709\u574f\uff0c\u4e5f\u8bb8\u6700\u597d\u7684\u529e\u6cd5\u5c31\u662f\u5728\u666e\u901a\u4ee3\u7801\u4e2d\u907f\u514d\u4f7f\u7528\u65b9\u6cd5\u91cd\u8f7d\u3002\n\u4e0d\u8fc7\u6709\u4e9b\u7279\u6b8a\u60c5\u51b5\u4e0b\u8fd8\u662f\u6709\u610f\u4e49\u7684\uff0c\u6bd4\u5982\u57fa\u4e8e\u6a21\u5f0f\u5339\u914d\u7684\u65b9\u6cd5\u91cd\u8f7d\u7a0b\u5e8f\u4e2d\u3002\n\u4e3e\u4e2a\u4f8b\u5b50\uff0c8.21\u5c0f\u8282\u4e2d\u7684\u8bbf\u95ee\u8005\u6a21\u5f0f\u53ef\u4ee5\u4fee\u6539\u4e3a\u4e00\u4e2a\u4f7f\u7528\u65b9\u6cd5\u91cd\u8f7d\u7684\u7c7b\u3002\n\u4f46\u662f\uff0c\u9664\u4e86\u8fd9\u4e2a\u4ee5\u5916\uff0c\u901a\u5e38\u4e0d\u5e94\u8be5\u4f7f\u7528\u65b9\u6cd5\u91cd\u8f7d\uff08\u5c31\u7b80\u5355\u7684\u4f7f\u7528\u4e0d\u540c\u540d\u79f0\u7684\u65b9\u6cd5\u5c31\u884c\u4e86\uff09\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5728Python\u793e\u533a\u5bf9\u4e8e\u5b9e\u73b0\u65b9\u6cd5\u91cd\u8f7d\u7684\u8ba8\u8bba\u5df2\u7ecf\u7531\u6765\u5df2\u4e45\u3002\n\u5bf9\u4e8e\u5f15\u53d1\u8fd9\u4e2a\u4e89\u8bba\u7684\u539f\u56e0\uff0c\u53ef\u4ee5\u53c2\u8003\u4e0bGuido van Rossum\u7684\u8fd9\u7bc7\u535a\u5ba2\uff1a\nFive-Minute Multimethods in Python"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.1"
    },
    "toc": {
      "base_numbering": 1,
      "nav_menu": {},
      "number_sections": true,
      "sideBar": true,
      "skip_h1_title": true,
      "title_cell": "Table of Contents",
      "title_sidebar": "Contents",
      "toc_cell": false,
      "toc_position": {},
      "toc_section_display": true,
      "toc_window_display": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}